<!-- 编辑器页面 -->
<template>
  <div class="main">
    <div id="components-layout" @mousedown="documentClickEvent">
      <a-tabs v-model:activeKey="activeTabKey" @change="changeTabs">
        <a-tab-pane id="editTemplate" key="editTemplate" tab="模板编辑">
          <a-layout>
            <a-layout-header>
              <!-- add components -->
              <add-components
                :addSvgVisible="addSvgVisible"
                @addSvgHandleOk="addSvgHandleOk"
                @cancel="hideAddSvgModal"
              />
              <!--add editTemplate-->
              <save-edit-template
                :editTemplateVisible="editTemplateVisible"
                :svgComponents="svgComponents"
                @confrimTemplateTitle="createTemplate"
                @hideTmeplateTitle="hideTmeplateTitle"
              />
              <div class="handler">
                <a-button
                  type="primary"
                  @click="saveEditTemplate"
                  style="margin-left: 20px"
                  >保存模板</a-button
                >
                <a-button
                  ghost
                  type="primary"
                  @click="restTemplateModel"
                  plain
                  style="margin-left: 20px"
                  >重置模板</a-button
                >
                <!-- <a-button
                  type="primary"
                  @click="testH"
                  style="margin-left: 20px"
                  ghost
                  >预览</a-button
                > -->
                <!-- <a style="margin-left: 20px">
                  <a-button type="primary" ghost @click="exportSvg"
                    >导出svg</a-button
                  >
                </a> -->
                <!-- <a style="margin-left: 20px">
                  <a-button type="primary" ghost @click="exportData"
                    >导出数据</a-button
                  >
                </a> -->
              </div>
            </a-layout-header>
            <a-layout class="pageMain">
              <a-layout-sider width="260px">
                <LeftToolBar
                  :svgInfoData="svgInfoData"
                  @deleteMenu="deleteMenu"
                  @showAddSvgModal="showAddSvgModal"
                />
              </a-layout-sider>
              <a-layout-content class="centerContain" id="centerContain">
                <div
                  ref="canvas"
                  class="canvansDiv"
                  :style="'transform: scale(' + scaleValue + ')'"
                  @mousemove="MouseMove"
                  @mousedown="MousedownCanvas"
                  @mouseup="MouseupCanvas"
                  @dblclick="DblClick"
                  @mousewheel="MouseWheel"
                >
                  <!--拖动辅助线-->
                  <div
                    id="guide-x"
                    ref="guidex_dom"
                    :style="'border-top: ' + 1 / scaleValue + 'px dashed #55f'"
                  ></div>
                  <div
                    id="guide-y"
                    ref="guidey_dom"
                    :style="'border-left: ' + 1 / scaleValue + 'px dashed #55f'"
                  ></div>
                  <div id="svgContainer" class="container" ref="svgContainer">
                    <!-- 画布 -->
                    <svg
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      xmlns:xlink="http://www.w3.org/1999/xlink"
                      :style="{
                        'background-image':
                          $store.state.BGIMG.TYPE != 'default'
                            ? `url(${$store.state.BGIMG.BASE64DATA})`
                            : '',
                        backgroundColor:
                          $store.state.BGIMG.TYPE == 'default' ? '#000000' : '',
                      }"
                      class="svgContent"
                      width="100%"
                      height="100%"
                      id="svgCanvas"
                    >
                      <defs />
                      <filter x="0" y="0" width="1" height="1" id="solid">
                        <feFlood flood-color="rgb(255,255,255)" />
                        <feComposite in="SourceGraphic" />
                      </filter>
                      <g
                        style="cursor: pointer"
                        v-for="(item, index) in svgLists"
                        :key="item"
                        :id="item.id"
                        :class="
                          selectSvgInfo.componentDataId == item.componentDataId
                            ? 'topo-layer-view-selected'
                            : ''
                        "
                        @mousedown="MousedownSvg(item, index, $event)"
                        :title="item.title"
                        :transform="
                          'translate(' +
                          item.svgPositionX +
                          ',' +
                          item.svgPositionY +
                          ')' +
                          'rotate(' +
                          item.angle +
                          ')' +
                          'scale(' +
                          item.size +
                          ')'
                        "
                        @contextmenu.prevent="contextmenuEvent"
                      >
                        <SvgComponents
                          :component_prop="item"
                          :svgInfoData="svgLists"
                        ></SvgComponents>
                      </g>
                    </svg>
                  </div>
                </div>
                <div class="zoonStyle">
                  <div style="text-color: black">
                    缩放：
                    <a-slider
                      :default-value="scaleValue"
                      :min="0.1"
                      :max="2"
                      :step="0.1"
                      @change="scaleValueChange"
                      style="width: 200px"
                    />
                  </div>
                </div>
              </a-layout-content>
              <a-layout-sider
                width="300px"
                v-if="selectSvgInfo && svgLists.length"
              >
                <RightToolBar
                  ref="rightToobar"
                  :svgInfo="selectSvgInfo"
                  :svgLists="svgLists"
                  :templateId="templateId"
                  @setTableAttr="setTableAttr"
                  @changeSvgInfo="changeSvgInfo"
                  @changeSvgComponentsStatus="changeSvgComponentsStatus"
                  @changeComponentsStatus="changeComponentsStatus"
                />
              </a-layout-sider>
            </a-layout>
          </a-layout>
        </a-tab-pane>
        <a-tab-pane id="TemplateLists" key="TemplateLists" tab="模板列表">
          <template-lists @editWaterTemplate="editWaterTemplate" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <!-- 右键菜单 -->
  <ul ref="contextMenuRef" class="contextMenu" v-show="display_contextmenu">
    <li
      v-for="(item, index) in contextmenu_data"
      :key="index"
      @click="rightMenuEvent(item)"
    >
      <p :class="item.enable ? '' : 'disabled'">
        {{ item.name }}
        <span class="shortcut">{{ item.hotkey }}</span>
      </p>
    </li>
  </ul>
</template>
<script>
import html2canvas from 'html2canvas';
import { message } from 'ant-design-vue';
import { Storage } from '@/util/storage.js';
import LeftToolBar from '@/components/LeftToolBar.vue';
import RightToolBar from '@/components/RightToolBar.vue';
import SvgComponents from '@/components/SvgComponents.vue';
import AddComponents from '@/components/addComponents.vue';
import SaveEditTemplate from '@/components/saveEditTemplate.vue';
import TemplateLists from '@/views/TemplateLists.vue';
import '@/assets/css/svgAnimation/index.css';
import {
  addComponent,
  listComponent,
  deleteComponent,
  userUploader,
  addWaterTemplate,
} from '@/network/api/index';
import {
  hotkeyCopy,
  hotkeyDel,
  hotkeyPutOnTop,
  hotkeyPutOnButtom,
  hotkeyPutOnUp,
  hotkeyPutOnDown,
} from '@/util/HotkeyFunc.js';
export default {
  components: {
    LeftToolBar,
    RightToolBar,
    SvgComponents,
    AddComponents,
    SaveEditTemplate,
    TemplateLists,
  },
  emits: ['editWaterTemplate'],
  data() {
    return {
      templateId: '',
      deviceHeight: '',
      activeTabKey: 'TemplateLists',
      editTemplateVisible: false,

      svgComponents: {
        templateName: '',
        remark: '',
        backgroundImg: '', //背景图
        previewImg: '', //自动截屏预览图片
        components: [], //组件列表
        waterTemplateId: '',
      },
      display_contextmenu: false,
      //鼠标右键
      contextmenu_data: [
        {
          name: '复制',
          type: 'copy',
          hotkey: 'Ctrl+C',
          enable: true,
        },
        {
          name: '删除',
          type: 'delete',
          hotkey: 'Delete',
          enable: false,
        },
        {
          name: '置于顶层',
          type: 'top',
          hotkey: 'Ctrl+→',
          enable: true,
        },
        {
          name: '置于底层',
          hotkey: 'Ctrl+←',
          type: 'bottom',
          enable: true,
        },
        {
          name: '置于上一层',
          type: 'addTop',
          hotkey: 'Ctrl+↑',
          enable: true,
        },
        {
          name: '置于下一层',
          hotkey: 'Ctrl+↓',
          type: 'nextBottom',
          enable: true,
        },
      ],
      addSvgVisible: false,
      svgInfoData: [], //接口获取到的组件数据
      shrink: true, //收缩状态  true收缩  false展开
      svgLists: [], //svg列表
      //鼠标位置
      mousePosition: {
        positionX: '',
        positiony: '',
      },
      selectSvg: {
        componentDataId: '', //要移动的svg
        Index: 0,
        mPositionX: 0, //选中svg时鼠标的x轴坐标
        mPositionY: 0, //选中svg时鼠标的y轴坐标
        pointX: 0, //选中svg时svg的x轴坐标
        pointY: 0, //选中svg时svg的y轴坐标
      },
      mouseStatus: 0, // 鼠标状态 1按下； 0弹起
      selectSvgInfo: '',
      clickType: '', //鼠标点击行为
      scaleValue: 1, //缩放倍数
    };
  },
  methods: {
    headleChangeColor(e) {
      console.log(e);
    },
    restTemplateModel() {
      this.svgLists = [];
      this.selectSvgInfo = '';
      this.svgComponents = {
        templateName: '',
        remark: '',
        backgroundImg: '',
        previewImg: '',
        components: [], //组件列表
        waterTemplateId: '',
      };
    },
    editWaterTemplate(val) {
      let _this = this;
      this.$nextTick(() => {
        let key = 'editTemplate';
        _this.templateId = val.waterTemplateId;
        _this.changeTabs(key);
        _this.svgLists = val.waterTemplateInfo.map((item) => {
          item.props = ['prop_data'];
          item.defaultAttr = JSON.parse(item.defaultAttr);
          item.size = Number(item.size);
          item.svgPositionX = Number(item.svgPositionX);
          item.svgPositionY = Number(item.svgPositionY);
          return item;
        });
        //组件
        let bgImg = {
          ID: val.base64Data ? '' : 'FirstOneBgImg',
          TYPE: val.base64Data ? 'bgImg' : 'default',
          BASE64DATA: val.base64Data ? val.base64Data : '#000000',
        };
        this.$store.setCurrentlySelectBase64DataAction(bgImg);
        _this.selectSvgInfo = _this.svgLists[0];
        _this.svgComponents.components = _this.svgLists;
        _this.svgComponents.templateName = val.templateName;
        _this.svgComponents.remark = val.remark;

        setTimeout(() => {
          _this.$refs.rightToobar.getTemplateGroup(val.waterTemplateId);
        }, 0);
      });
    },
    changeTabs(activeKey) {
      this.activeTabKey = activeKey;
      this.initDiv(activeKey);
      switch (activeKey) {
        case 'editTemplate':
          this.getLeftComponents();
          this.watchEditTemplate();
          break;
      }
    },
    initDiv(val) {
      this.$nextTick(() => {
        const oIframe = document.getElementById(val);
        // const deviceWidth = document.documentElement.clientWidth;
        this.deviceHeight = document.documentElement.clientHeight;
        // oIframe.style.width = (Number(deviceWidth)-220) + 'px'; //数字是页面布局宽度差值
        oIframe.style.height = Number(this.deviceHeight) - 120 + 'px'; //数字是页面布局高度差
        const centerContain = document.getElementById('centerContain');
        centerContain.scrollLeft = centerContain.scrollWidth / 2;
      });
    },
    saveEditTemplate() {
      this.editTemplateVisible = !this.editTemplateVisible;
    },
    createTemplate() {
      this.svgComponents.components = JSON.parse(JSON.stringify(this.svgLists));
      if (!this.svgComponents.components.length) {
        message.error('模板内容不能为空哦~');
      } else {
        //获取编辑的图片链接
        this.selectSvgInfo = {};
        this.getImgUrl(this.$refs.svgContainer).then((url) => {
          this.svgComponents.previewImg = url; //自动截屏预览图片
          this.svgComponents.backgroundImg = this.$store.state.BGIMG.BASE64DATA; //背景图片
          //translate to string
          this.svgComponents.components
            ? this.svgComponents.components.forEach((item) => {
                item.defaultAttr = JSON.stringify(item.defaultAttr);
              })
            : '';
          this.svgComponents.waterTemplateId = this.templateId
            ? this.templateId
            : '';
          this.$httpRequest(addWaterTemplate, this.svgComponents, 'post').then(
            (res) => {
              this.templateId = res.data;
              message.success('保存成功~');
              Storage.set('svgComponents', this.svgComponents.components);
              this.svgComponents = {};
              this.selectSvgInfo = this.svgLists[0];
            }
          );
        });
      }
    },
    convertCanvasToImage(src) {
      let formData = new FormData();
      // this.formData.append('source_from','webpage_upload')//在formdata加入需要的参数
      formData.append('file', this.dataURItoBlob(src), 'templateImg.jpg');
      return formData;
    },
    dataURItoBlob(dataURI) {
      //图片转成Buffer
      var byteString = atob(dataURI.split(',')[1]);
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    hideTmeplateTitle() {
      this.editTemplateVisible = false;
    },
    contextmenuEvent(e) {
      const contextMenuRef = this.$refs.contextMenuRef;
      this.display_contextmenu = true;
      contextMenuRef.style.left = e.pageX + 'px';
      contextMenuRef.style.top = e.pageY + 'px';
      this.contextmenu_data.map((m) => (m.enable = true));
      //判断当前选中组件的index
      if (this.svgLists.length === 1) {
        //禁用下移
        this.contextmenu_data[3].enable = false;
        this.contextmenu_data[5].enable = false;
        //禁用上移
        this.contextmenu_data[2].enable = false;
        this.contextmenu_data[4].enable = false;
      } else if (this.selectSvg.Index === 0) {
        //禁用下移
        this.contextmenu_data[3].enable = false;
        this.contextmenu_data[5].enable = false;
      } else if (this.selectSvg.Index === this.svgLists.length - 1) {
        //禁用上移
        this.contextmenu_data[2].enable = false;
        this.contextmenu_data[4].enable = false;
      }
    },
    //右键菜单操作
    rightMenuEvent(item) {
      switch (item.type) {
        case 'copy':
          if (!item.enable) return;
          hotkeyCopy(this.svgLists, this.selectSvg, this);
          this.display_contextmenu = false;
          console.log(this.svgLists);
          break;
        case 'delete':
          if (!item.enable) return;
          hotkeyDel(this.svgLists, this.selectSvg);
          this.display_contextmenu = false;
          break;
        case 'top':
          if (!item.enable) return;
          hotkeyPutOnTop(this.svgLists, this.selectSvg);
          this.display_contextmenu = false;
          break;
        case 'bottom':
          if (!item.enable) return;
          hotkeyPutOnButtom(this.svgLists, this.selectSvg);
          this.display_contextmenu = false;
          break;
        case 'addTop':
          if (!item.enable) return;
          hotkeyPutOnUp(this.svgLists, this.selectSvg);
          this.display_contextmenu = false;
          break;
        case 'nextBottom':
          if (!item.enable) return;
          hotkeyPutOnDown(this.svgLists, this.selectSvg);
          this.display_contextmenu = false;
          break;
      }
    },
    documentClickEvent(e) {
      if (e.button !== 2) {
        this.display_contextmenu = false;
      }
    },
    showAddSvgModal() {
      this.addSvgVisible = true;
    },
    hideAddSvgModal() {
      this.addSvgVisible = false;
    },
    exportSvg() {
      // this.getImgUrl(this.$refs.testImage, 'svgContainer').then((url) => {
      //   console.log(url);
      // });
    },
    addSvgHandleOk(val) {
      this.$httpRequest(
        addComponent,
        {
          createType: val.createType,
          defaultAttr:
            val.imgType == 'img' ? null : JSON.stringify(val.defaultAttr),
          imgType: val.imgType,
          priviewImg: val.priviewImg,
          template: val.template,
          // template:
          //   "<text x='0' y='0' :class='(prop_data.defaultAttr.fontEffect.val.selectval)' :font-family='(prop_data.defaultAttr.fontFamily.val.selectval)'  :font-size='prop_data.defaultAttr.fontSize.val' :stroke='(prop_data.defaultAttr.fontEffect.val.selectval?prop_data.defaultAttr.strokeColor.val:prop_data.defaultAttr.fillColor.val)'  :fill='prop_data.defaultAttr.fillColor.val'>{{prop_data.defaultAttr.text.val}}</text>",
          title: val.title,
          type: val.type,
        },
        'post'
      ).then(() => {
        message.success('添加成功~');
        this.addSvgVisible = false;
        this.getLeftComponents();
      });
    },
    //获取图片路径
    getImgUrl(modal) {
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          html2canvas(modal, {
            backgroundColor: '#fff',
            allowTaint: true,
            useCORS: true, // 解决资源跨域问题
            logging: true,
          })
            .then((canvas) => {
              let imgsrc = canvas.toDataURL('image/png');
              this.$httpRequest(
                userUploader,
                this.convertCanvasToImage(imgsrc),
                'post',
                'multipart/form-data'
              )
                .then((res) => {
                  resolve(res.filePath);
                })
                .catch((err) => {
                  reject(err);
                });
            })
            .catch((err) => {
              reject(err);
            });
        });
      });
    },
    exportData() {
      let svgInfo = {
        svgComponentsLists: this.svgLists,
        svgGroupLists: Storage.get('svgGroupLists'),
      };
      localStorage.setItem('svgInfo', JSON.stringify(svgInfo));
      let datastr =
        'data:text/json;charset=utf-8,' +
        encodeURIComponent(JSON.stringify(svgInfo));
      let download = document.createElement('a');
      download.setAttribute('href', datastr);
      download.setAttribute('download', 'download.json');
      download.click();
      download.remove();
    },
    MouseMove(e) {
      let _this = this;
      if (this.clickType == 'draggable') {
        if (this.mouseStatus == 0) {
          return;
        }
        const { clientX, clientY } = e;
        let componentDataId = this.selectSvg.componentDataId;
        //排除当前元素剩下的所有svg元素的列表
        let anyPositionList = this.svgLists.filter(function (list) {
          return list.componentDataId != componentDataId;
        });
        //将要移动的元素坐标设备为鼠标坐标
        let svgPositionX = this.selectSvg.pointX;
        let svgPositionY = this.selectSvg.pointY;
        svgPositionX += (clientX - this.selectSvg.mPositionX) / this.scaleValue;
        svgPositionY += (clientY - this.selectSvg.mPositionY) / this.scaleValue;
        setTimeout(function () {
          //少于十个像素自动吸附
          //从所有的x坐标列表中查与当前坐标少于10个像素的组件是否存在
          let exitsAdsorbX = anyPositionList.filter(function (list) {
            return (
              -10 < list.svgPositionX - svgPositionX &&
              list.svgPositionX - svgPositionX < 10
            );
          });
          if (exitsAdsorbX.length > 0) {
            svgPositionX = exitsAdsorbX[0].svgPositionX;
          }
          //y轴相同 横向坐标自动吸附
          let exitsAdsorbY = anyPositionList.filter(function (list) {
            return (
              -10 < list.svgPositionY - svgPositionY &&
              list.svgPositionY - svgPositionY < 10
            );
          });
          if (exitsAdsorbY.length > 0) {
            svgPositionY = exitsAdsorbY[0].svgPositionY;
          }
          _this.svgLists[_this.selectSvg.Index].svgPositionX = svgPositionX;
          _this.svgLists[_this.selectSvg.Index].svgPositionY = svgPositionY;
          //从所有的x坐标列表中查当前坐标是否存在
          let exitsNowX = anyPositionList.filter(function (list) {
            return list.svgPositionX === svgPositionX;
          });
          if (exitsNowX.length > 0) {
            _this.$refs.guidey_dom.style.setProperty(
              'left',
              svgPositionX - 1 / _this.scaleValue + 'px'
            );
            _this.$refs.guidey_dom.style.display = 'inline';
          } else {
            _this.$refs.guidey_dom.style.display = 'none';
          }
          //从所有的y坐标列表中查当前坐标是否存在
          let exitsNowY = anyPositionList.filter(function (list) {
            return list.svgPositionY === svgPositionY;
          });
          if (exitsNowY.length > 0) {
            _this.$refs.guidex_dom.style.setProperty(
              'top',
              svgPositionY - 1 / _this.scaleValue + 'px'
            );
            _this.$refs.guidex_dom.style.display = 'inline';
          } else {
            _this.$refs.guidex_dom.style.display = 'none';
          }
        }, 1);
      } else if (this.clickType == 'draw') {
        if (this.mouseStatus == 0) {
          return;
        }
        this.selectSvgInfo.handPoint.endX = e.offsetX;
        this.selectSvgInfo.handPoint.endY = e.offsetY;
      }
    },
    MousedownCanvas(e) {
      if (this.clickType == 'draggable') {
        return;
      }

      if (
        this.$store.state.CurrentlySelectedToolBar &&
        this.$store.state.CurrentlySelectedToolBar.CreateType == 'draw'
      ) {
        //根据类型和鼠标位置创建组件
        let svgItem = {
          //不用后端的唯一id，考虑到复制组件问题
          componentDataId: this.$UCore.GenUUid(),
          imgType: this.$store.state.CurrentlySelectedToolBar.ImgType,
          createType: this.$store.state.CurrentlySelectedToolBar.CreateType,
          title: this.$store.state.CurrentlySelectedToolBar.Title,
          type: this.$store.state.CurrentlySelectedToolBar.Type,
          typeName: this.$store.state.CurrentlySelectedToolBar.TypeName,
          props: ['prop_data'],
          template: this.$store.state.CurrentlySelectedToolBar.Template,
          svgColor: this.$store.state.CurrentlySelectedToolBar.Color,
          defaultAttr: JSON.parse(
            JSON.stringify(
              this.$store.state.CurrentlySelectedToolBar.Default_Attr
            )
          ),
          hideAddGroup: false, //group status
          svgPositionX: e.offsetX,
          svgPositionY: e.offsetY,
          handPoint: {
            startX: e.offsetX,
            startY: e.offsetY,
            endX: e.offsetX,
            endY: e.offsetY,
          },
          componentDataSource: null, //组件数据源
          dataKeyId: '', //数值keyId
          dataKeyName: '',
          stateKeyName: '',
          stateKeyId: '', //状态keyId
          size: 1,
          angle: 0,
          // translate: `translate(${this.mousePosition.positionX},${this.mousePosition.positionY})`,
        };
        this.svgLists.push(svgItem);
        this.selectSvgInfo = svgItem;
        this.mouseStatus = 1;
        this.clickType = 'draw';
      }
    },
    MousedownSvg(item, index, e) {
      this.$store.clearCurrentlySelectedToolBarAction();
      //从数组里面根据index找到当前元素
      this.selectSvg.componentDataId = item.componentDataId;
      this.selectSvg.Index = index;
      this.mouseStatus = 1;
      this.selectSvg.mPositionX = e.clientX;
      this.selectSvg.mPositionY = e.clientY;
      this.selectSvg.pointX = item.svgPositionX;
      this.selectSvg.pointY = item.svgPositionY;
      this.selectSvgInfo = this.svgLists[index];
      this.clickType = 'draggable';
    },
    MouseupCanvas() {
      if (this.mouseStatus == 0) {
        return;
      }
      this.$refs.guidex_dom.style.display = 'none';
      this.$refs.guidey_dom.style.display = 'none';
      // if (this.$store.state.CurrentlySelectedToolBar.Type != '') {
      //   return;
      // }
      // this.selectSvg.ID = '';
      this.mouseStatus = 0;
      // this.clickType = '';
      if (this.clickType == 'draggable') {
        this.clickType = '';
      }
      if (this.clickType == 'draw') {
        if (
          this.selectSvgInfo.handPoint.startX ==
            this.selectSvgInfo.handPoint.endX &&
          this.selectSvgInfo.handPoint.startY ==
            this.selectSvgInfo.handPoint.endY
        ) {
          //根据当前id找到当前元素的index
          let selectSvgIndex = this.svgLists.indexOf(
            this.svgLists.filter(
              (f) => f.componentDataId == this.selectSvgInfo.componentDataId
            )[0]
          );
          this.svgLists.splice(selectSvgIndex, 1);
          this.selectSvg = {};
          this.selectSvgInfo = {};
        }
      }
      // this.$store.state.CurrentlySelectedToolBar = {};
    },
    MouseWheel(e) {
      //获取当前选中组件
      let selectSvgInfo = this.selectSvgInfo;
      if (
        selectSvgInfo == undefined ||
        selectSvgInfo == null ||
        selectSvgInfo == ''
      ) {
        return;
      }
      e.preventDefault();
      //判断滚轮方向 -100是往上滑 100是下滑
      let svgZoom = e.deltaY < 0 ? 0.1 : -0.1;
      selectSvgInfo.size += svgZoom;
      selectSvgInfo.size = parseFloat(selectSvgInfo.size.toFixed(1));
      if (selectSvgInfo.size < 1) {
        selectSvgInfo.size = 1;
      }
    },
    DblClick() {
      this.selectSvgInfo = '';
      this.$store.clearCurrentlySelectedToolBarAction();
    },
    deleteMenu(id) {
      this.$httpRequest(deleteComponent, { componentId: id }, 'delete').then(
        () => {
          message.success('删除操作成功~');
          this.getLeftComponents();
        }
      );
    },
    //设置表格属性
    setTableAttr(id, rowCount, colCount) {
      //根据当前id找到当前表格的index
      let tableIndex = this.svgLists.indexOf(
        this.svgLists.filter((f) => f.id == id)[0]
      );
      if (tableIndex == -1) {
        return;
      }
      let svgType = this.svgLists.filter((f) => f.id == id)[0].type;
      if (svgType != 'TableSvg') {
        return;
      }
      let tableData = [];
      for (let r = 0; r < rowCount; r++) {
        let tableColDataList = [];
        for (let c = 0; c < colCount; c++) {
          if (
            this.svgLists[tableIndex].tableData.length >= r + 1 &&
            this.svgLists[tableIndex].tableData[r].cols.length >= c + 1
          ) {
            tableColDataList.push(
              this.svgLists[tableIndex].tableData[r].cols[c]
            );
          } else {
            let tableColData = {
              id: this.$UCore.GenUUid(),
              val: `${r + 1}行${c + 1}列`,
            };
            tableColDataList.push(tableColData);
          }
        }
        let tableRowData = {
          cols: tableColDataList,
        };
        tableData.push(tableRowData);
      }
      this.svgLists[tableIndex].tableData = tableData;
    },
    scaleValueChange(newValue) {
      this.scaleValue = newValue;
    },
    changeSvgInfo(val) {
      this.selectSvgInfo = val;
    },
    //改变svgLists状态
    changeSvgComponentsStatus(list) {
      this.svgLists.forEach((svgItem) => {
        list.forEach((item) => {
          item.componentDataId == svgItem.componentDataId
            ? Object.assign(svgItem, item)
            : '';
        });
      });
    },
    //改变组件状态
    changeComponentsStatus(arr) {
      let svgInfo = JSON.parse(
        localStorage.getItem('svgInfo')
      ).svgComponentsLists;
      if (svgInfo) {
        svgInfo.forEach((svgItem) => {
          arr.forEach((componentsItem) => {
            componentsItem.componentDataId == svgItem.componentDataId
              ? Object.assign(svgItem, componentsItem)
              : '';
          });
        });
        this.svgLists = svgInfo;
        let svgInfo = localStorage.getItem('svgInfo');
        svgInfo.svgComponentsLists = this.svgLists;
        localStorage.setItem('svgInfo', JSON.stringify(svgInfo));
      }
    },
    getLeftComponents() {
      //请求接口获取组件
      this.$httpRequest(listComponent).then((res) => {
        res.data
          ? res.data.forEach((item) => {
              item.defaultAttr = JSON.parse(item.defaultAttr);
            })
          : '';
        this.svgInfoData = res.data ? res.data : [];
      });
    },
    watchEditTemplate() {
      let _this = this;
      this.$nextTick(() => {
        _this.initDiv('editTemplate');
        let canvasdiv = _this.$refs.canvas;
        canvasdiv.addEventListener(
          'dragover',
          function (e) {
            e.preventDefault();
          },
          false
        );
        canvasdiv.addEventListener(
          'drop',
          function (e) {
            e.preventDefault();
            if (
              _this.$store.state.CurrentlySelectedToolBar.CreateType !=
              'draggable'
            ) {
              return;
            }
            let eChartsOption =
              _this.$store.state.CurrentlySelectedToolBar.EChartsOption;
            //根据类型和鼠标位置创建组件
            let svgItem = {
              componentDataId: _this.$UCore.GenUUid(),
              imgType: _this.$store.state.CurrentlySelectedToolBar.ImgType,
              createType:
                _this.$store.state.CurrentlySelectedToolBar.CreateType,
              title: _this.$store.state.CurrentlySelectedToolBar.Title,
              template: _this.$store.state.CurrentlySelectedToolBar.Template,
              props: ['prop_data'],
              type: _this.$store.state.CurrentlySelectedToolBar.Type,
              typeName: _this.$store.state.CurrentlySelectedToolBar.TypeName,
              svgColor: _this.$store.state.CurrentlySelectedToolBar.Color,
              svgPositionX: e.offsetX,
              svgPositionY: e.offsetY,
              echartsOption: eChartsOption ? JSON.parse(eChartsOption) : '',
              size: 1,
              angle: 0,
              componentDataSource: null, //组件数据源
              dataKeyId: '', //数值keyId
              dataKeyName: '',
              stateKeyName: '',
              stateKeyId: '', //状态keyId
              hideAddGroup: false, //group status
              defaultAttr: JSON.parse(
                JSON.stringify(
                  _this.$store.state.CurrentlySelectedToolBar.Default_Attr
                )
              ),
            };
            _this.svgLists.push(svgItem);
            _this.selectSvgInfo = svgItem;
          },
          false
        );
      });
    },
  },
  mounted() {},
  created() {
    let _this = this;
    //当前页面监视键盘输入
    document.onkeydown = function (e) {
      //获取当前选中组件
      let selectSvgInfo = _this.selectSvgInfo;
      if (
        selectSvgInfo == undefined ||
        selectSvgInfo == null ||
        selectSvgInfo == ''
      ) {
        return;
      }
      //事件对象兼容
      let e1 = e || window.event || arguments.callee.caller.arguments[0];
      //键盘按键判断:左箭头->37;上箭头->38；右箭头->39;下箭头->40
      if (e1 && !e1.ctrlKey && e1.keyCode == 37) {
        e.preventDefault();
        selectSvgInfo.svgPositionX -= 1;
      } else if (e1 && !e1.ctrlKey && e1.keyCode == 38) {
        e.preventDefault();
        selectSvgInfo.svgPositionY -= 1;
      } else if (e1 && !e1.ctrlKey && e1.keyCode == 39) {
        e.preventDefault();
        selectSvgInfo.svgPositionX += 1;
      } else if (e1 && !e1.ctrlKey && e1.keyCode == 40) {
        e.preventDefault();
        selectSvgInfo.svgPositionY += 1;
      }
      //ctrl  c
      else if (e1 && e1.ctrlKey && e1.keyCode == 67) {
        if (!_this.editTemplateVisible) {
          e.preventDefault();
          let copySvgInfoStr = JSON.stringify(selectSvgInfo);
          let copySvgInfo = JSON.parse(copySvgInfoStr);
          copySvgInfo.componentDataId = _this.$UCore.GenUUid();
          copySvgInfo.svgPositionX = selectSvgInfo.svgPositionX + 10;
          copySvgInfo.svgPositionY = selectSvgInfo.svgPositionY + 10;
          _this.svgLists.push(copySvgInfo);
          _this.selectSvgInfo = copySvgInfo;
        }
      }
      //deleted
      else if (e1 && e1.keyCode == 46) {
        e.preventDefault();
        //根据当前id找到当前元素的index
        let selectSvgIndex = _this.svgLists.indexOf(
          _this.svgLists.filter(
            (f) => f.componentDataId == selectSvgInfo.componentDataId
          )[0]
        );
        _this.svgLists.splice(selectSvgIndex, 1);
      } //上移一层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowUp') {
        e.preventDefault();
        hotkeyPutOnUp(_this.svgLists, _this.selectSvg);
      }
      //下移一层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowDown') {
        e.preventDefault();
        hotkeyPutOnDown(_this.svgLists, _this.selectSvg);
      }
      //置于底层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowLeft') {
        e.preventDefault();
        hotkeyPutOnButtom(_this.svgLists, _this.selectSvg);
      }
      //置于顶层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowRight') {
        e.preventDefault();
        hotkeyPutOnTop(_this.svgLists, _this.selectSvg);
      }
    };
    this.getLeftComponents();
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
::-webkit-scrollbar {
  width: 6px;
  height: 5px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #f2f2f2;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #9e9e9e;
}
.createTemplate {
  margin: 150px auto;
  width: 500px;
}

.button {
  display: flex;
}

.button > div {
  text-align: center;
  flex: 1;
}

#components-layout .ant-layout-header {
  position: relative;
  left: 0;
  right: 0;
  top: 0;
  line-height: 50px;
  height: 50px;
  background: #fff;
  color: rgb(0, 0, 0);
  padding: 0;
  z-index: 2;
  box-shadow: 1px 1px 5px #ddd;
}

.pageMain {
  position: absolute;
  left: 0;
  right: 0;
  top: 110px;
  bottom: 0;
  // overflow: auto;
}

.centerContain {
  // position: absolute;
  left: 260px;
  right: 300px;
  top: 0;
  bottom: 0;
  z-index: 1;
  overflow: auto !important;
  overflow-x: auto !important;
  transition: all 0.3s;
  z-index: 111;

  &.fixed {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  .canvansDiv {
    width: 1920px;
    height: 1080px;
    transform-origin: left top;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
  }

  .canvas-content {
    width: 1920px;
    height: 1080px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
  }

  .btns-content {
    position: fixed;
    bottom: 10px;
    right: 320px;
    left: 280px;

    button {
      margin-left: 10px;
    }
  }
}

#components-layout .ant-layout-sider {
  background: #fff;
  color: rgb(167, 164, 164);
}

#guide-x {
  display: none;
  position: absolute;
  width: 100%;
  left: 0px;
  top: 0px;
}

#guide-y {
  display: none;
  position: absolute;
  height: 100%;
  left: 0px;
  top: 0px;
}

.ant-slider {
  margin-bottom: 16px;
}

.topo-layer {
  width: 100%;
  height: 100%;
  position: absolute;
  transform-origin: left top;
  overflow: auto;

  background-image: linear-gradient(
      45deg,
      #ccc 25%,
      transparent 25%,
      transparent 75%,
      #ccc 75%,
      #ccc
    ),
    linear-gradient(
      45deg,
      #ccc 25%,
      transparent 25%,
      transparent 75%,
      #ccc 75%,
      #ccc
    );
  background-size: 20px 20px;
  background-position: 0 0, 10px 10px;
}

.resize-left-top {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  left: -5px;
  top: -5px;
  cursor: nwse-resize;
}

.resize-left-bottom {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  left: -5px;
  bottom: -5px;
  cursor: nesw-resize;
}

.resize-right-top {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  right: -5px;
  top: -5px;
  cursor: nesw-resize;
}

.resize-right-bottom {
  position: absolute;
  height: 10px;
  width: 10px;
  background-color: white;
  border: 1px solid #0cf;
  right: -5px;
  bottom: -5px;
  cursor: nwse-resize;
}

.topo-layer-view-selected {
  outline: 1px solid #0cf;
}

.contextMenu {
  position: absolute;
  z-index: 99999;
  background: #ffffff;
  padding: 5px 0;
  margin: 0px;
  display: block;
  border-radius: 5px;
  box-shadow: 2px 5px 10px rgba(0, 0, 0, 0.3);
}

.contextMenu li {
  list-style: none;
  padding: 0px;
  margin: 0px;
}
.container {
  height: 100%;
}

.contextMenu .shortcut {
  width: 115px;
  text-align: right;
  float: right;
}

.contextMenu p {
  text-decoration: none;
  display: block;
  padding: 0px 15px 1px 20px;
  margin: 0;
  user-select: none;
  -webkit-user-select: none;
}

.contextMenu p:hover {
  background-color: #0cf;
  color: #ffffff;
  cursor: default;
}

.contextMenu .disabled {
  color: #999;
}

.contextMenu .disabled:hover {
  color: #999;
  background-color: transparent;
}

.contextMenu li.separator {
  border-top: solid 1px #e3e3e3;
  padding-top: 5px;
  margin-top: 5px;
}

.zoonStyle {
  position: fixed;
  bottom: 75px;
  z-index: 99;
  color: #fff;
  background: rgba(0, 0, 0, 0.3);
}
.svgContent {
  background-size: cover;
  min-height: 100vh;
  -webkit-transform-origin: top left;
  transform-origin: top left;
  overflow: hidden;
}

.handler {
  text-align: right;
}
</style>
